package com.funnyx.config;

import com.funnyx.service.baseservice.GetService;
import com.funnyx.service.baseservice.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@EnableConfigurationProperties(ElasticProp.class)
public class ElasticsearchAutoConfiguration {

  private final ElasticProp elasticProp;

  public ElasticsearchAutoConfiguration(ElasticProp elasticProp) {
    this.elasticProp = elasticProp;
  }

  @Bean
  public RestHighLevelClient restHighLevelClient() {

    String[] nodes = elasticProp.getNodes().split(",");
    HttpHost[] hosts = new HttpHost[nodes.length];
    for (int i = 0; i < nodes.length; i++) {
      hosts[i] = HttpHost.create(nodes[i]);
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    // 设置连接时间为30秒，socket通信时间为5分钟
    restClientBuilder.setRequestConfigCallback(
        requestConfigBuilder ->
            requestConfigBuilder.setConnectTimeout(30000).setSocketTimeout(300000));

    if (StringUtils.isNotBlank(elasticProp.getUser())
        && StringUtils.isNotBlank(elasticProp.getPassword())) {
      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials("elastic", "AFE#qr33"));

      restClientBuilder.setHttpClientConfigCallback(
          httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
          });
    }

    return new RestHighLevelClient(restClientBuilder);
  }

  @Bean
  @ConditionalOnProperty(prefix = "spring.es", name = "search.enable", havingValue = "true")
  public SearchService searchService() {
    return new SearchService();
  }

  @Bean
  @ConditionalOnProperty(prefix = "spring.es", name = "get.enable", havingValue = "true")
  public GetService getService() {
    return new GetService();
  }
}
